package handel

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"order-car/cache"
	"order-car/model"
	"strconv"
	"time"
)

func CarAdd(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	data := model.Car{
		CarCode: car_code,
		CarName: car_name,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_num, _ := strconv.Atoi(c.PostForm("order_num"))
	car_id, _ := strconv.Atoi(c.PostForm("car_id"))
	data := model.Order{
		OrderCode: order_code,
		OrderNum:  order_num,
		CarId:     car_id,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderList(c *gin.Context) {
	/*
			SELECT
		  orders.order_code AS OrderCode,
		  orders.order_num AS OrderNum,
		  cars.car_code AS CarCode,
		  cars.car_name AS CarName
		FROM
		  orders
		  LEFT JOIN cars ON orders.car_id = cars.id
	*/
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list []model.CarOrder
	redis_key := "order_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select(
				"orders.order_code AS OrderCode",
				"orders.order_num AS OrderNum",
				"cars.car_code AS CarCode",
				"cars.car_name AS CarName",
			).
			Joins("LEFT JOIN cars ON orders.car_id = cars.id").Offset(offset).Limit(size).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var total int64
	model.DB.Model(model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "展示成功",
		"data":  list,
		"total": total,
	})
}
func OrderFind(c *gin.Context) {
	id := c.Query("id")
	var list model.CarOrder
	redis_key := "order_find_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select(
				"orders.order_code AS OrderCode",
				"orders.order_num AS OrderNum",
				"cars.car_code AS CarCode",
				"cars.car_name AS CarName",
			).
			Joins("LEFT JOIN cars ON orders.car_id = cars.id").
			Where("orders.car_id=?", id).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": list,
	})
}
